<?php
/**
 * Created by IntelliJ IDEA.
 * User: jiam
 * Date: 4/11/2022
 * Time: 12:05 AM
 */

namespace WebApp\lib\util;


use DOMDocument;
use DOMXPath;
use function PHPSTORM_META\type;

class phpInfoUtil
{
    /**
     * phpInfoUtil constructor.
     */
    private function __construct()
    {
    }

    /**
     * @var phpInfoUtil
     */
    private static $instance;

    /**
     * @return phpInfoUtil
     */
    public static function getInstance(): phpInfoUtil
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getEnableArr() {
        $arr = [];
        foreach($this->getPhpInfo()->query("//h2") as $item) {
            $arr[] = ($item->textContent);
        }

//        var_dump($this->getPhpInfo()->query("//td[@class='v']"));exit;


//        $pattern = "/\s(.*)\s"."support"."\s=>\s"."enabled"."/";
//        $matches = [];
//        preg_match_all($pattern, $this->getPhpInfo(),  $matches);
        return $arr;
    }

    public function getVersionArr() {
        $arr = [];
        foreach ($this->getPhpInfo()->query("//td[@class='e']") as $item) {
            if (Util::hasString($item->textContent, "version")) {
                $res = $this->getPhpInfo()->query("//td[@class='e' and text()='{$item->textContent}']/following-sibling::*");
                $arr[trim(str_replace("version", "", $item->textContent))] = trim($res[0]->textContent);
            }
        }

//        $pattern = "/\s(.*)\s"."version"."\s=>\s(.*)/";
//        $matches = [];
//        preg_match_all($pattern, $this->getPhpInfo(),  $matches);
//        $dict = [];
//        foreach ($matches[1] ?? [] as $index => $item) {
//            $dict[$item] = $matches[2][$index];
//        }
        return $arr;
    }


    private $php_info = null;

    /**
     * @return DOMXpath
     */
    private function getPhpInfo(): DOMXpath
    {
        if (null === $this->php_info) {
            $str = strtolower(file_get_contents("http://www.real.com/?func=info"));
            $arr = [];
            preg_match_all("/<body>(.*)<\/body>/Uis", $str, $arr);
            $dom = new DOMDocument();
            @$dom->loadHtml($arr[1][0]);
            $dom->normalize();
            $xpath = new DOMXpath($dom);
            $this->php_info = $xpath;
        }


        return $this->php_info;
    }
}